package liangaes

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"errors"
)

func PKCS5Padding(cipherText []byte, blockSize int) []byte {
	padding := blockSize - len(cipherText)%blockSize
	padText := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(cipherText, padText...)
}

func PKCS5UnPadding(origData []byte, blockSize int) ([]byte, error) {
	length := len(origData)
	if length == 0 {
		return origData, nil
	} else if length%blockSize != 0 {
		return nil, errors.New("unpadding data is not full block")
	}

	unPadding := int(origData[length-1])
	if unPadding > blockSize {
		return nil, errors.New("unpadding data size error")
	}

	for i := length - unPadding; i < length; i++ {
		if origData[i] != byte(unPadding) {
			return nil, errors.New("unpadding data error")
		}
	}

	return origData[:(length - unPadding)], nil
}

func AesCbcNoSaltEncrypt(origData, key []byte, iv []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	blockSize := block.BlockSize()
	origData = PKCS5Padding(origData, blockSize)
	blockMode := cipher.NewCBCEncrypter(block, iv[:blockSize])
	encrypted := make([]byte, len(origData))
	blockMode.CryptBlocks(encrypted, origData)
	return encrypted, nil
}

func AesCbcNoSaltDecrypt(encrypted, key []byte, iv []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	blockSize := block.BlockSize()
	if len(encrypted)%blockSize != 0 {
		return nil, errors.New("encrypted data is not full block")
	}

	blockMode := cipher.NewCBCDecrypter(block, iv[:blockSize])
	origData := make([]byte, len(encrypted))
	blockMode.CryptBlocks(origData, encrypted)
	origData, err = PKCS5UnPadding(origData, blockSize)
	if err != nil {
		return nil, err
	}
	return origData, nil
}

func AesCbcNoSaltDecryptWithoutUnpadding(encrypted, key []byte, iv []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	blockMode := cipher.NewCBCDecrypter(block, iv)
	origData := make([]byte, len(encrypted))
	blockMode.CryptBlocks(origData, encrypted)
	return origData, nil
}
